package cn.openea.perpartner.link.web.entity.dto;

import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.link.constant.CommonConstants;
import cn.openea.perpartner.link.constant.enums.AppType;
import cn.openea.perpartner.link.web.entity.ShareLinkConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.function.Function;

/**
 * @author ysk
 * @version 1.0.1
 * @Description TODO
 * @createTime 2023年05月22日 00:17:00
 */
@Component
public class ShareLinkConfigDTOFactory {

    @Resource
    private RedisCache redisCache;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    public static class InfoDTO {
        private Long id;
        /**
         * 名称
         */
        private String linkName;
        /**
         * 分享的key 唯一，自动生成
         */
        private String shareKey;
        /**
         * 跳转页面路径
         */
        private String pagePath;
        /**
         * 程序类型
         */
        private String appType;
        /**
         * 程序名称
         */
        private String appName;
        /**
         * 访问次数
         */
        private Long visitsNum;
        /**
         * 创建人
         */
        private String createUser;

        private String createTime;

        private String updateTime;
    }

    public Function<ShareLinkConfig, InfoDTO> toInfoDTO = (shareLinkConfig) -> {
        if (shareLinkConfig == null) {
            return null;
        }
        InfoDTO infoDTO = new InfoDTO();
        BeanUtils.copyProperties(shareLinkConfig, infoDTO);
        infoDTO.setAppName(Objects.requireNonNull(AppType.getByCode(infoDTO.getAppType())).getName());
        // 去redis中获取保存的访问点击率
        Integer number = redisCache.getNumber(CommonConstants.REDIS.REDIS_SHARE_LINK_VISITS_NUM + shareLinkConfig.getId());
        if (number != null) {
            infoDTO.setVisitsNum(shareLinkConfig.getVisitsNum() + number);
        }
        return infoDTO;
    };

}
